package com.tianquan.miracle.listener.core;/**
 * @author starsea
 * @date 2024-10-12 下午4:08
 */

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * @BelongsProject: uploaddemo
 * @BelongsPackage: com.tianquan.miracle.listener
 * @Author: tianquan
 * @CreateTime: 2024-10-12  16:08
 * @Description: 事件源管理器
 * @Version: 1.0
 */
public class EventSourceManager implements EventSource {

    private final List<EventListener> listeners = new ArrayList<>();

    @Override
    public void addEventListener(EventListener<?> listener) {
        listeners.add(listener);
    }

    @Override
    public void addEventListeners(List<EventListener> listeners) {
        this.listeners.addAll(listeners);
    }

    @Override
    public void removeEventListener(EventListener<?> listener) {
        listeners.remove(listener);
    }

    @Override
    public void publishEvent(EventObject eventObject) {
        // 遍历所有监听器，找到对应的事件调用onEvent方法
        for (EventListener listener : listeners) {
            // 获取到当前监听器监听的事件类型
            Type[] interfaces = listener.getClass().getGenericInterfaces();
            for (Type type : interfaces) {
                if (type instanceof ParameterizedType parameterizedType) {
                    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                    if (actualTypeArguments.length > 0 && actualTypeArguments[0] instanceof Class<?> genericType) {
                        if (genericType.isInstance(eventObject)) listener.onEvent(eventObject);
                    }
                }
            }
        }
    }
}
